package org.xy.manager;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.xy.bean.Bean;
import org.xy.bean.Beans;

public class BeanDefinitionReader {
	private static Map<String, Bean> beanMap = new HashMap<String, Bean>();
	private static String FILE_PATH = "./src/main/resources/manual/bean.xml";

	public static int TYPE_XML = 1;
	public static int TYPE_PG = 2;

	static {
		try {

			File file = new File(FILE_PATH);
			JAXBContext jaxbContext = JAXBContext.newInstance(Beans.class);
			Unmarshaller jaxbUnMarshaller = jaxbContext.createUnmarshaller();

			Beans beans = (Beans) jaxbUnMarshaller.unmarshal(file);

			if (beans != null) {
				beanMap.clear();
				for (Bean bean : beans.getBeans()) {
					beanMap.put(bean.getName(), bean);
				}
			}

		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}

	public static Map<String, Bean> getBeans(int type) {

		if (TYPE_XML == type) {
			return beanMap;
		}

		if (beanMap == null || beanMap.isEmpty()) {
			beanMap = new HashMap<String, Bean>();
		}

		beanMap.put("Car", new Bean("Car", "org.xy.bean.Car", new String[] {
				"Wheel", "Chair" }));
		beanMap.put("Chair", new Bean("Chair", "org.xy.bean.Chair", null));
		beanMap.put("Wheel", new Bean("Wheel", "org.xy.bean.Wheel",
				new String[] { "Screw" }));
		beanMap.put("Screw", new Bean("Screw", "org.xy.bean.Screw", null));

		return beanMap;
	}

}
